import { useState, useEffect, useRef } from 'react';
import './GameStats.css';

export const GameStats = () => {
  const [fps, setFps] = useState(0);
  const frameCountRef = useRef(0);
  const lastTimeRef = useRef(performance.now());
  const requestRef = useRef();

  useEffect(() => {
    // 单一的帧率计算函数
    const updateFps = () => {
      // 增加帧计数
      frameCountRef.current += 1;
      
      const now = performance.now();
      const delta = now - lastTimeRef.current;
      
      // 每秒更新一次FPS值
      if (delta >= 1000) {
        // 计算FPS并更新状态
        setFps(Math.round((frameCountRef.current * 1000) / delta));
        
        // 重置计数器和时间
        frameCountRef.current = 0;
        lastTimeRef.current = now;
      }
      
      // 继续循环
      requestRef.current = requestAnimationFrame(updateFps);
    };

    // 启动帧率更新循环
    requestRef.current = requestAnimationFrame(updateFps);

    // 清理函数
    return () => {
      cancelAnimationFrame(requestRef.current);
    };
  }, []); // 只在组件挂载和卸载时运行

  return (
    <div className="game-stats">
      <div className="stat-item">FPS: {fps}</div>
    </div>
  );
}; 